<template>
  <div class="voice-library">
    <page-box>
      <template #top>
        <alert-msg
          content="语音应用与IVR导航中对客户侧的引导。语音支持wav格式，仅支持单声道，非wav格式系统将转码，转码后音频可能会有损失。语音文件大小不得超过3M。语音文件上传后系统后台会进行审核，审核通过后可用于呼叫中心相关配置。"
        >
          <template #icon>
            <i class="MC_iconfont MC_icon-xinxi-mian"></i>
          </template>
        </alert-msg>
      </template>
      <template #search>
        <search-form :fieldList="fieldList" :form="form" @onSearchFun="searchFun"></search-form>
      </template>
      <template #btn>
        <el-button @click="searchFun">查询</el-button>
        <el-button type="primary" @click="addVoice">新建</el-button>
      </template>
      <template #table>
        <resize-table
          :topHeight="48"
          :headers="tableHeaders"
          :data="tableData"
          :pagingData="pagingData"
          @onPageChange="handleCurrentChange"
          @onPageSizeChange="handleSizeChange"
          :showPagination="true"
        >
          <template #waitingVoice="{ scope }">
            <span v-if="scope.row.voiceType === 'moh'">等待语音</span>
            <span v-else-if="scope.row.voiceType === 'general_voice'">普通语音</span>
            <span v-else>系统预置</span>
          </template>
          <template #status="{ scope }">
            <span v-if="scope.row.status === 'not_pass'"><i class="fail" />未通过</span>
            <span v-else-if="scope.row.status === 'pass'"><i class="success" />已通过</span>
            <span v-else-if="scope.row.status === 'pending_review'"><i class="waiting" />待审核</span>
          </template>
          <template #voiceOprate="{ scope }">
            <audio-play
              :row="{
                url: scope.row.fileUrl,
                isplay: scope.row.isplay,
                _id: scope.row.id
              }"
              @onAudioClick="restTablePlay"
            ></audio-play>
            <!-- 系统预置的禁止下载 -->
            <a :href="scope.row.fileUrl" target="_blank" v-if="scope.row.voiceType !== 'system_preset'" download>
              <i class="MC_iconfont MC_icon-shangchuan-xiazai"></i>
            </a>
          </template>
          <template #oprate="{ scope }">
            <span class="edit" @click="editVoice(scope.row)">编辑</span>
            <span class="delete" @click="deleteVoice(scope.row)">删除</span>
          </template>
        </resize-table>
      </template>
    </page-box>
    <upload-voice ref="voiceInfo" @onUpdateList="searchFun"></upload-voice>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, toRefs, getCurrentInstance, markRaw } from 'vue'
import searchForm from '@/common/components/base-form/form.vue'
import resizeTable from '@/common/components/resize-table/index.vue'
import uploadVoice from './components/add-voice.vue'
import pageBox from '@common/components/page-box.vue'
import alertMsg from '@common/components/alert/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { delVoice, getVoice } from '@app/call-center/apis/voice-library'
import audioPlay from '@/common/components/audio/audio-operate.vue'
import mcCache from '@/common/utils/mc-get-cache'
import bus from '@/common/utils/bus'
import deleteIcon from '@/common/components/delete-icon/index.vue'
interface State {
  fieldList: Record<string, unknown>[]
  form: Record<string, unknown>
  tableHeaders: Record<string, unknown>[]
  tableData: Record<string, unknown>[]
  pagingData: Record<string, number>
}

const statusChoices: Record<string, unknown>[] = [
  {
    label: '全部',
    value: ''
  },
  {
    label: '已通过',
    value: 'pass'
  },
  {
    label: '待审核',
    value: 'pending_review'
  },
  {
    label: '未通过',
    value: 'not_pass'
  }
]

const typeChoices: Record<string, unknown>[] = [
  {
    label: '全部',
    value: ''
  },
  {
    label: '系统预置',
    value: 'system_preset'
  },
  {
    label: '普通语音',
    value: 'general_voice'
  },
  {
    label: '等待语音',
    value: 'moh'
  }
]

const instance: any = getCurrentInstance()

const state: State = reactive({
  fieldList: [
    {
      name: '语音名称',
      field: 'name',
      type: 'text'
    },
    {
      name: '类型',
      field: 'voiceType',
      type: 'dropdown',
      choices: typeChoices,
      placeholder: '全部'
    },
    {
      name: '状态',
      field: 'status',
      type: 'dropdown',
      choices: statusChoices,
      placeholder: '全部'
    }
  ],
  form: {
    status: '',
    voiceType: ''
  },
  tableHeaders: [
    { label: '语音名称', prop: 'name', show: true },
    { label: '类型', prop: 'waitingVoice', show: true, custom: true },
    { label: '文件名', prop: 'fileName', show: true },
    { label: '备注', prop: 'description', show: true },
    { label: '状态', prop: 'status', show: true, custom: true },
    { label: '语音操作', prop: 'voiceOprate', show: true, custom: true },
    { label: '操作', prop: 'oprate', show: true }
  ],
  tableData: [],
  pagingData: {
    page: 1,
    total: 200,
    limit: 10
  }
})
// 点击列表的听取录音，重置其他数据
const restTablePlay = (data: any) => {
  const arr: any = []
  state.tableData.forEach((item: any) => {
    if (item.id === data._id) {
      item.isplay = data.isplay
    } else {
      item.isplay = false
    }
    arr.push(item)
  })
  state.tableData = arr
}
const handleCurrentChange = (page: number) => {
  state.pagingData.page = page
  getData()
}

const handleSizeChange = (size: number) => {
  state.pagingData.limit = size
  getData()
}

const addVoice = () => {
  instance?.refs.voiceInfo.openUploadVoice('add', {})
}

const editVoice = (row: any) => {
  instance?.refs.voiceInfo.openUploadVoice('edit', row)
}

const deleteVoice = (row: any) => {
  ElMessageBox.confirm('删除后将不可找回，请谨慎操作', '确认要删除此语音吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    title: '删除',
    icon: markRaw(deleteIcon)
  })
    .then(() => {
      delVoice(row.id).then((res) => {
        if (res.success) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          searchFun()
          // 更新pinia
          mcCache.$deleteCache('voiceLibrary', 'id', row.id, 'hasObj')
        }
      })
    })
    .catch()
}

const searchFun = () => {
  state.pagingData.page = 1
  getData()
}

const getData = () => {
  const sendData = {
    ...state.form,
    pageSize: state.pagingData.limit,
    pageNumber: state.pagingData.page
  }
  getVoice(sendData).then((res) => {
    if (res.success && res.data) {
      state.tableData = res.data.list || []
      bus.emit('restAudioStatus')
      state.pagingData.total = res.data.page.total || 0
    }
  })
}

onMounted(() => {
  getData()
})

const { fieldList, form, tableHeaders, tableData, pagingData } = toRefs(state)
</script>

<style lang="stylus">
.voice-library {
  a {
    text-decoration: none;
  }

  .edit, .delete {
    color: var(--mc-main-color);
    cursor: pointer;

    &.edit {
      margin-right: 16px;
    }
  }

  .fail, .success, .waiting {
    display: inline-block;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 8px;
    vertical-align: middle;

    &.fail {
      background: var(--mc-error-color);
    }

    &.success {
      background: var(--mc-success-color);
    }

    &.waiting {
      background: var(--mc-warning-color);
    }
  }

  .MC_icon-shangchuan-xiazai {
    font-size: 20px;
    color: var(--mc-main-color);
    margin-left: 18px;
  }
}
</style>
